<?php

class LogoManager
{
    public static function getImage($logo_data)
    {
        if ($logo_data) {
            $logo_data = base64_decode($logo_data);
        } else {
            $blank_file = sfContext::getInstance()->getConfiguration()->getRootDir().'/web/images/1px-white.png';
            $logo_data = file_get_contents($blank_file);
        }

        $finfo = finfo_open();
        $mime = finfo_buffer($finfo, $logo_data, FILEINFO_MIME);
        $pos = strpos($mime, ';');
        if ($pos !== false)
            $mime = substr($mime, 0, $pos);
        sfContext::getInstance()->getResponse()->setHttpHeader('Cache-control', 'no-cache', true);
        sfContext::getInstance()->getResponse()->setHttpHeader('Content-type', $mime, true);

        return $logo_data;
    }

    public static function resizeLogo($data)
    {
        $image = @imagecreatefromstring($data);
        if(!$image)
            return null;

        // Computations
        $image_width  = imagesx($image);
        $image_height = imagesy($image);
        $goal_width   = 110;
        $goal_height  = 80;

        $scale_factor = min($goal_width/$image_width, $goal_height/$image_height);
        $new_width    = round($image_width * $scale_factor);
        $new_height   = round($image_height * $scale_factor);
        $delta_width  = floor(($goal_width - $new_width) / 2);
        $delta_height = floor(($goal_height - $new_height) / 2);

        // Creates the new image
        $new_image = imagecreatetruecolor($goal_width, $goal_height);
        $background_color = imagecolorallocate($new_image, 255, 255, 255);
        imagefill($new_image, 0, 0, $background_color);
        imagecopyresampled($new_image, $image, $delta_width, $delta_height, 0, 0,
                           $new_width, $new_height, $image_width, $image_height);

        // Exports the new image
        $tmp_name = tempnam(null, 'vtns-logo-');
        imagepng($new_image, $tmp_name);

        $new_data = file_get_contents($tmp_name);
        unlink($tmp_name);

        // Frees ressources
        imagecolordeallocate($new_image, $background_color);
        imagedestroy($image);
        imagedestroy($new_image);

        return $new_data;
    }
}
